﻿/**
* 模块名：质量管理
* 程序名: 综合文档管理  
* Copyright(c) 2014 xiaoping
**/
var viewModel = function (data) {
    var self = this;
    this.idField = data.idField;
    this.urls = data.urls;
    this.resx = data.resx;
    this.dataSource = data.dataSource;
    this.form = ko.mapping.fromJS(data.form);
    delete this.form.__ko_mapping__;
    this.grid = {
        size: { w: 239, h: 95 },
        url: "/api/qms/FileContent",
        queryParams: ko.observable(),
        pagination: true,
        singleSelect: true
    };
    this.grid.queryParams(data.form);
    //发布
    this.publishClick = function () {
        var row = self.grid.datagrid('getSelected');
        if (!row) return com.message('warning', self.resx.noneSelect);
        com.message('confirm', "确认要发布该文档吗?", function (b) {
            if (b) {
                com.ajax({
                    type: 'POST', url: "/api/qms/FileContent/Publish/" + row[self.idField], success: function () {
                        com.message('success', "发布成功!");
                        self.searchClick();
                    }
                });
            }
        });
    };
    this.searchClick = function () {
        var param = ko.toJS(this.form);
        this.grid.queryParams(param);
    };

    this.clearClick = function () {
        self.form.FileContent_ValidDate("");
        self.form.FileContent_Title("");
        self.form.FileContent_IsPublic("");
        self.form.ApproveState("");
        //        $.each(self.form, function () { this(''); });
        this.searchClick();
    };
    this.editClick = function () {
        //        var row = self.grid.datagrid('getSelected');
        //        //        if (row["ApproveState"] == undefined) {
        //        //            return;
        //        //        }
        //        self.gridEdit.begin(row);
        var row = self.grid.datagrid('getSelected');
        if (!row) return com.message('warning', self.resx.noneSelect);
        com.openTab(self.resx.detailTitle, self.urls.edit + row[self.idField]);
    };
    this.grid.onDblClickRow = this.editClick;
    //    this.gridEdit = new com.editGridViewModel(this.grid);
    //    this.grid.onDblClickRow = self.gridEdit.begin;
    //    this.grid.onClickRow = self.gridEdit.ended;
    //获取名称
    //    this.grid.OnBeforeDestroyEditor = function (editors, row) {
    //        row['FileContent_Bmmc'] = editors['FileContent_Bmbh'].target.lookup('getText');
    //    };
    //    this.grid.OnAfterCreateEditor = function (edt, row) {
    //        var Unit = edt['FileContent_Title'].target;
    //        var calc = function () {
    //            row['FileContent_Bmmc'] = edt['FileContent_Bmbh'].target.lookup('getText');
    //        };
    //        Unit.blur(calc);
    //        //该列必须为有edit属性
    //        com.readOnlyHandler('input')(edt["FileContent_FileBh"].target, true);
    //    };
    this.tree = {
        method: 'GET',
        checkbox: false,
        url: '/api/qms/FileContent/GetFileTypes2/' + data.isTypeId,
        //        queryParams: ko.observable(),
        //queryParams: { FileType_Lb: data.isTypeId },
        loadFilter: function (d) {
            var filter = utils.filterProperties(d.rows || d, ['FileType_Bh as id', 'FileType_Mc as text', 'FileType_ParentBh as pid']);
            var data = utils.toTreeData(filter, 'id', 'pid', "children");
            return [{ id: '', text: '所有类别', children: data}];
        },
        onSelect: function (node) {

            self.CodeType(node.id);
        }
    };

    this.CodeType = ko.observable();
    this.CodeType.subscribe(function (value) {
        //订阅(向后台传文件分类参数)
        self.grid.queryParams({ FileContent_TypeBh: value, FileType_Lb: data.isTypeId });
    });

    this.refreshClick = function () {
        //window.location.reload();
        var param = ko.toJS(this.form);
        param.FileContent_TypeBh = self.CodeType();
        this.grid.queryParams(param);
        //self.grid.queryParams({ FileContent_TypeBh: self.CodeType() });
    };
    this.addClick = function () {
        if (self.CodeType() == undefined || self.CodeType() == "") return com.message('warning', "请先在左边选择要添加的类别!");
        com.ajax({
            type: 'GET',
            url: '/api/qms/FileContent/getnewcode',
            success: function (d) {
                var arg = d + ";" + self.CodeType();
                com.openTab(self.resx.detailTitle, self.urls.edit + arg);
            }
        });

        //        if (!self.CodeType()) return com.message('warning', '请先在左边选择要添加的类别！');
        //        com.ajax({
        //            type: 'GET',
        //            url: '/api/qms/FileContent/getnewcode', //流水号
        //            success: function (d) {
        //                var row = { FileContent_TypeBh: self.CodeType(), FileContent_FileBh: d };
        //                self.gridEdit.addnew(row);
        //            }
        //        });
    };

    //    this.deleteClick = self.gridEdit.deleterow;
    this.deleteClick = function () {
        var row = self.grid.datagrid('getSelected');
        if (!row) return com.message('warning', self.resx.noneSelect);
        com.message('confirm', self.resx.deleteConfirm, function (b) {
            if (b) {
                com.ajax({
                    type: 'DELETE', url: self.urls.remove + row[self.idField], success: function () {
                        com.message('success', self.resx.deleteSuccess);
                        self.refreshClick();
                    }
                });
            }
        });
    }
    this.saveClick = function () {
        self.gridEdit.ended();
        var post = { list: self.gridEdit.getChanges() };
        if (self.gridEdit.isChangedAndValid()) {
            com.ajax({
                url: '/api/qms/FileContent/edit',
                data: ko.toJSON(post),
                success: function (d) {
                    com.message('success', '保存成功！');
                    self.gridEdit.accept();
                }
            });
        }
    };
    //上传(文件)
    this.upClick = function () {
        var row = self.grid.datagrid('getSelected');
        if (row == null) {
            com.message('error', "请选择文档记录!");
            return;
        }
        if (row["FileContent_FileBh"] == undefined) {
            com.message('error', "文档编号不能为空!");
            return;
        }
        com.dialog({
            title: "&nbsp;上传文档_" + row["FileContent_Title"],
            iconCls: 'icon-node_tree',
            width: 400,
            height: 230,
            url: "/qms/FileContent/UpLoad/" + row["FileContent_FileBh"],
            viewModel: function (w) {
                var that = this;
                this.confirmClick = function () {
                };
                this.cancelClick = function () {
                    w.dialog('close');
                };
            }
        });
    };
    //文档类别字典
    this.typeClick = function () {
        com.dialog({
            title: "&nbsp;文档类别",
            iconCls: 'icon-node_tree',
            width: 600,
            height: 410,
            html: "#type-template",
            viewModel: function (w) {
                var that = this;
                this.grid = {
                    width: 585,
                    height: 330,
                    idField: '_id', //虚拟主键
                    treeField: 'FileType_Bh',
                    url: "/api/qms/FileContent/GetFileTypes",
                    //                    queryParams: ko.observable(),
                    queryParams: { FileType_Lb: data.isTypeId },
                    loadFilter: function (d) {
                        //采用这种写法
                        d = utils.copyProperty(d.rows || d, ["FileType_Bh", "IconClass"], ["_id", "iconCls"], false);
                        return utils.toTreeData(d, '_id', 'FileType_ParentBh', "children");
                    }
                };
                this.gridEdit = new com.editTreeGridViewModel(this.grid);
                this.grid.OnAfterCreateEditor = function (editors, row) {
                    if (!row._isnew) {
                        com.readOnlyHandler('input')(editors["FileType_Bh"].target, true);
                    }
                };
                //                this.grid.onClickRow = that.gridEdit.begin;
                this.grid.onDblClickRow = that.gridEdit.begin;
                this.grid.onClickRow = that.gridEdit.ended;
                this.grid.toolbar = [
                    { text: '新增', iconCls: 'icon-add1', handler: function () {
                        com.ajax({
                            type: 'GET',
                            url: '/api/qms/FileContent/GetNewTypeCode', //流水号
                            success: function (d) {
                                var row = { FileType_Bh: d, FileType_UserCode: self.dataSource.userCode, FileType_Lb: data.isTypeId, FileType_IsPublic: "false" };
                                that.gridEdit.addnew(row);
                            }
                        });
                    }
                    }, '-',
                    { text: '删除', iconCls: 'icon-cross', handler: function () {
                        var row = that.grid.treegrid('getSelected');
                        if (!row) return com.message('warning', "请选择要删除的行!");

                        com.ajax({
                            type: 'DELETE',
                            url: '/api/qms/FileContent/DeleteTypeCode/' + row["FileType_Bh"], //流水号
                            success: function (d) {
                                that.gridEdit.deleterow(); //移除行
                                com.message('success', '删除成功！');
                            }
                        });

                    }
                    }
                ];
                this.confirmClick = function () {
                    if (that.gridEdit.ended() && that.gridEdit.isChangedAndValid()) {
                        var list = that.gridEdit.getChanges(['FileType_Bh', 'FileType_ParentBh', 'FileType_UserCode', 'FileType_Mc', 'FileType_Remark', 'FileType_Lb', 'FileType_IsPublic']);
                        com.ajax({
                            url: '/api/qms/FileContent/EditFileType/',
                            data: ko.toJSON({ list: list }),
                            success: function (d) {
                                that.cancelClick();
                                self.tree.$element().tree('reload');
                                com.message('success', '保存成功！');
                            }
                        });
                    }
                };
                this.cancelClick = function () {
                    w.dialog('close');
                };
            }
        });
    };
};
var fundownload = function (bh) {
    //下载
    alert(bh);
    // window.location.href = '/qms/FileContent/DownLoad?id=' + row["FileContent_FileBh"];
};

//原来写法上传【可作导入Excel】（暂时保留）
var initUploader = function (fileId) {
    //上传初始化
    fileId = 1;
    $('#uploader').find(".l-btn-text").fineUploader({
        request: { endpoint: '/api/qms/FileContent/postfile?id=' + fileId },
        multiple: false,    //设成false，这样就不能多选了，只能选一个
        validation: {
            allowedExtensions: ['doc', 'docx', 'xls'],
            sizeLimit: 51200 // 50 kB = 50 * 1024 bytes
        },
        text: { uploadButton: '上传' },
        autoUpload: true
    }).on('upload', function (id, name) {
        $.messager.progress({ title: '请稍等', msg: '正在上传...', interval: 0 });
    }).on('complete', function (event, id, name, response) {
        //上传成功
        $.messager.progress('close');
        if (response.success) {
            com.message('success', response.message);
            //刷新
            vmInstance.refreshClick();
        }
    }).on('progress', function (target, id, name, loaded, total) {
        $.messager.progress('bar').progressbar('setValue', Math.ceil(loaded * 100 / total));
        if (loaded >= total) {
            $.messager.progress('close');
            $.messager.progress({ title: '请稍等', msg: '上传完成，正在导入处理...', interval: 300, text: '' });
        }
    }).on('error', function (target, id, name, reason, maybeXhrOrXdr) {
        com.message('error', reason);
    });
    $("#uploader").css("overflow", "hidden");
    $(".qq-upload-button").css("overflow", "");
    $(".qq-drop-processing,.qq-upload-list").hide();
}